<template>
  <view class="wrap">
    <view class="cell" @click="toSelectAddress">
      <view class="label" v-if="order.address.realName" >
        <view class="location-detail bold ellipsis"><text :class="'address-tag address-tag-' + order.address.tag">{{['默认', '家', '公司'][order.address.tag - 1]}}</text>{{order.address.province}}{{order.address.city}}{{order.address.district}}{{order.address.address}}</view>
        <view class="phone">{{order.address.realName}}（先生） {{order.address.phone}}</view>
      </view>
      <view class="label" v-else>
        <text>请选择地址</text>
      </view>
      <text class="iconfont icon-xiangyou"></text>
    </view>
    <view class="item">
      <view class="title">
        <view class="name">
          <image :src="order.logo" mode="aspectFill" />{{order.shopName}}</view>
        <text class="status">{{['待支付', '待提货', '待归还', '已完成'][item.status - 1]}}</text>
      </view>
      <view class="main" v-for="(goods, index) in order.goodsArr" :key="goods.id">
        <image :src="goods.pic" mode="aspectFill"></image>
        <view class="info">
          <view class="name ellipsis-2">{{goods.goodsName}}</view>
          <view class="price">¥{{goods._price}}/次</view>
		  <view class="descript">额外费用请与工作人员结算</view>
        </view>
      </view>
    </view>
	<view class="appoint">
	  <view class="cell">
		<view class="label">预约日期:</view>
		<picker mode="date" @change="onDateChange" :start="tommorrow">
			<view>{{order.appointDate || '请选择预约日期'}}</view>
		</picker>
	  </view>
	  <view class="cell">
		<view class="label">预约费用</view>
		<text>¥{{order.totalPrice}}</text>
	  </view>
	</view>
	<view class="bottom-btn" v-if="order.status === 1 || order.status === 4">
		<div class="row"><text v-if="order.status === 1">{{order.totalPrice}}</text></div>
		<button type="default" @click="pay"  v-if="order.status === 1">支付</button>
		<button type="default" @click="cancel" v-if="order.status === 4">取消</button>
	</view>
  </view>
</template>

<script>
  import uniCard from "@/components/uni-card/uni-card"
  import {Order, User} from '@/apis'
  import {utils, numeral} from '@/utils'
  import config from '@/config'
  
  var d = new Date();
  d.setTime(d.getTime()+24*60*60*1000);
  
  var tommorrow = d.format('yyyy-MM-dd');
  export default {
    data() {
      return {
		tommorrow,
        message: '',
        isLoading: false,
        delivery: false,
        options: {},
        order: {
		  appointDate: '',
          goods: [],
          address: {}
        }
      };
    },
    components: {uniCard},
    methods: {
      getOrderDetail () {
        if (this.isLoading) return
        this.isLoading = true
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        Order.getOrderDetail({
          data: {
            form: {},
            pagination: {},
            query: {
              orderNumber: this.options.number
            }
          }
        }).then(res => {
          console.log('获取订单详情成功')
          console.log(res.data);
          if (res.data.code !== 200) {
            this.message = res.data.message
            uni.showToast({
              title: res.data.message || '订单异常',
              icon: 'none'
            })
            return
          }
          let order = res.data.body
          let total = 0, totalDeposit = 0, totalPrice = 0
          order.goodsArr.map(item => {
            totalPrice += item.price
            // 计算价格、押金
            item._price = numeral(item.price).divide(100).format('0.00')
          })
          
          order.total = numeral(totalPrice).add(totalDeposit).format('0.00')
          order._total = numeral(totalPrice).add(totalDeposit).divide(100).format('0.00')
          order.totalPrice = numeral(totalPrice).divide(100).format('0.00')
          this.order = order
		  
          
        }, err => console.error(err)).finally(() => {
          this.isLoading = false
          uni.hideLoading()
        })
      },
      toSelectAddress () {
		  console.log('选择地址');
        uni.navigateTo({
          url: '/pages/myAddress/myAddress?type=select'
        })
      },
      deleteItem (orderNumber) {
        if (this.isLoading) return
        this.isLoading = true
        utils.wxAlert('您确定删除此订单？').then(result => {
          Order.deleteOrder({data: {
            form: {},
            query: {
              orderNumber: orderNumber
            },
            pagination: {}
          }}).then(res => {
            if (res.data.code !== 200) {
              utils.wxToastFail(res.data.message)
              return
            }
            utils.wxToastSuccess().then(() => {
              utils.routerBack()
            })
          }).catch(err => console.error(err)).finally(() => {
            this.isLoading = false
            uni.hideLoading()
          })
        })
      },
      deliveryChange (e) {
        console.log('是否配送', e)
        this.delivery = e.detail.value
      },
      pay () {
        let that = this
        // 判断是否选择了地址
        if (!this.order.address) {
          uni.showToast({
            title: '请选择地址',
            icon: 'none'
          })
          return
        }
		if (!this.order.appointDate) {
			utils.wxToast('请选择预约时间');
			return;
		}
        if (this.isLoading) return
        this.isLoading = true
        utils.wxLoading()
        const userInfo = uni.getStorageSync('userInfo')
        console.log(this.order)
        let item = utils.deepClone(this.order)
        User.prePayment({
          data: {
            form: {
              "device_info": "1",
              "body": "商品描述",
              "detail": "商品详情",
              "out_trade_no": item.orderNumber,
              "total_fee": +item.total,
              "spbill_create_ip": "0.0.0.0",
              "time_start": Date.now(),
              "notify_url": "http://www.weixin.qq.com/wxpay/pay.php",
              "product_id": utils.randomWord(false, 16),
              "openid": userInfo.openid
            }
          }
        }).then(res => {
          console.log('请求支付接口')
          console.log(res)
		  
          let result = res.data.body
		  if (result.code == -1) {
			  // 订单已支付，请勿重复支付
			  utils.wxToast(result.message)
			  return
		  }
          uni.requestPayment({
            nonceStr: result.nonceStr,
            timeStamp: result.timeStamp,
            package: result.packageInfo,
            paySign: result.sign,
            signType: 'MD5',
            success (payRes) {
              console.log('支付完成')
              console.log(payRes)
              Order.updateOrder({ data: {
                form: {
                  updateTime: utils.formatTime(new Date()),
                  orderNumber: item.orderNumber,
                  status: 2,
				  addressId: that.order.address.id
                },
                query: {},
                pagination: {}
              }}).then(res => {
                uni.showToast({
                  title: '支付完成',
                  icon: 'success'
                });
                console.log('更新支付状态', res)
                that.getOrderDetail()
              }).catch(err => console.log(err))
              this.updateOrder(item)
            },
            fail: (err) => {
              console.log('支付失败');
              console.error(err)
              this.isLoading = false
              uni.hideLoading()
              utils.wxToastFail('放弃支付')
			  //如果是测试环境，放弃支付也算支付成功
			  if (!config.isProd) {
				  this.updateOrder(item)
			  }
            },
            complete () {
              uni.hideLoading()
            }
          })
        }).catch(err => {
          utils.wxToastFail('支付失败')
        }).finally(() => {
          this.isLoading = false
        })
      },
	  onDateChange (e) {
		  this.order.appointDate = e.detail.value
		  this.$mp.page.setData({
			  order: this.order
		  })
	  },
	  /**
	   * @param {Object} item
	   */
	  updateOrder (item) {
		// 订单置为待确认
		this.order.status = 4;
		this.$mp.page.setData({
		  order: this.order
		})
		  
		Order.updateOrder({ data: {
		form: {
		  updateTime: utils.formatTime(new Date()),
		  orderNumber: item.orderNumber,
		  status: 4,
		  addressId: this.order.address.id,
		  appointDate: this.order.appointDate,
		  payTotal: numeral(this.order.totalPrice).multiply(100).value()
		},
		query: {},
		pagination: {}
		}}).then(res => {
		uni.showToast({
		  title: '支付完成',
		  icon: 'success'
		})
		console.log('更新支付状态', res)
		that.getOrderDetail()
		}).catch(err => console.log(err))
	  },
	  cancel () {
		  utils.wxAlert('确定要取消订单嘛？').then(res => {
			  console.log('确定取消订单')
			  Order.updateOrder({
				  data: {
					  form: {
						  orderNumber: this.order.orderNumber,
						  status: 7
					  }
				  }
			  }).then(res => {
				  console.log('取消订单成功')
				  console.log(res)
				  if (res.data.code === 200) {
					  this.order.status = 7
					  this.$mp.page.setData({
						  order: this.order
					  })
					utils.wxAlert('取消订单成功')
				  }
			  })
		  })
	  }
    },
    mounted (options) {
      this.options = this.$scope.options
      this.getOrderDetail()
    }
  }
</script>

<style lang="scss">
  page {
    background-color: #EFEFEF;
  }
  .appoint {
	  margin-top: 20rpx;
	  picker {
		  font-size: 24rpx;
	  }
  }
  .cell {
    box-sizing: border-box;
    padding: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 1rpx;
    background-color: #FFF;
	&+.cell {
		border-top: #EFEFEF 1rpx solid;
	}
    .label {
      color: #333333;
      font-size: 28rpx;
      .location-detail {
        font-weight: bold;
        max-width: 70%;
      }
    }
    .value {
      flex: 1;
      font-size: 28rpx;
    }
    .time {
      color: #0CB9F2;
      text-align: right;
    }
  }
  .item {
    box-sizing: border-box;
    margin-top: 20rpx;
    padding: 0 20rpx;
    background-color: #FFF;

    .title {
      color: #333333;
      font-size: 30rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: #EFEFEF 1rpx solid;
      padding: 20rpx 0;

      .name {
        display: flex;
        align-items: center;

        image {
          width: 44rpx;
          height: 44rpx;
          margin-right: 20rpx;
          background-color: #D8D8DD;
          border-radius: 50%;
        }
      }

      .status {
        font-weight: normal;
        color: #FF4A4A;
      }
    }

    .main {
      box-sizing: border-box;
      padding: 20rpx 0;
      display: flex;

      image {
        flex-shrink: 0;
        width: 140rpx;
        height: 140rpx;
        border-radius: 10rpx;
        background-color: #D8D8D8;
      }

      .info {
        flex: 1;
        box-sizing: border-box;
        padding-left: 20rpx;

        .name {
          color: #333333;
          font-size: 24rpx;
          height: 100rpx;
          line-height: 1.5;
        }

        .price {
          color: #FF4A4A;
          font-size: 24rpx;
          box-sizing: border-box;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-weight: bold;
        }
		.descript {
			color: #999;
			font-size: 20rpx;
		}
      }
    }

    .btn-group {
      display: flex;
      align-items: center;
      box-sizing: border-box;
      padding: 20rpx 0;
      border-top: #EFEFEF 1rpx solid;
      flex-direction: row-reverse;

      .total {
        color: #333333;
        font-size: 24rpx;
        line-height: 40rpx;
        flex-justify-self: flex-end;
        margin-right: auto;

        .total-price {
          text {
            color: #FF4A4A;
          }
        }

        .count {
          color: #666;
        }
      }

      button {
        width: 120rpx;
        height: 58rpx;
        border: #FF4A4A 2rpx solid;
        border-radius: 29rpx;
        margin: 10rpx;
        color: #FF4A4A;
        font-size: 28rpx;
        line-height: 58rpx;
        background-color: #FFF;
      }
    }
  }
  .amount-info {
    font-size: 28rpx;
    color: #333333;
    display: flex;
    align-items: center;
    justify-content: space-between;
    text {
      font-weight: bold;
      padding-right: 20rpx;
    }
  }
  .order-info {
    color: #333333;
    font-size: 28rpx;
  }
  .mt {
    margin-top: 20rpx;
  }
  .message {
    color: #999999;
    font-size: 18px;
    line-height: 36px;
    text-align: center;
    padding-top: 100px;
  }
  .address-tag {
	  width: 84rpx;
	  display: inline-block;
	  text-align: center;
	  padding: 10rpx 0;
	  border-radius: 5rpx;
	  font-size: 24rpx;
	  font-weight: normal;
	  margin-right: 10rpx;
  }
  .address-tag-1 {
	  background-color: #EFEFEF;
	  color: #333;
  }
  .address-tag-2 {
	  background-color: #1890FF;
	  color: #FFF;
  }
  .address-tag-3 {
	  background-color: #f0ad4e;
	  color: #FFF;
  }
  .bottom-btn {
	  position: absolute;
	  left: 0;
	  right: 0;
	  bottom: 0;
	  height: 100rpx;
	  display: flex;
	  align-items: center;
	  box-sizing: border-box;
	  padding: 20rpx;
	  background-color: #fff;
	  justify-content: space-between;
	  .row {
		  flex: 1;
		  display: flex;
	  }
	  text {
		  color: #E02020;
		  font-size: 32rpx;
		  &::before {
			  content: "￥";
			  font-size: 24rpx;
		  }
	  }
	  button {
		  width: 230rpx;
		  height: 60rpx;
		  display: block;
		  background-color: #FF4A4A;
		  font-size: 28rpx;
		  color: #FFFFFF;
		  line-height: 60rpx;
		  border-radius: 30rpx;
		  margin: 0;
		  &:hover {
			  background-color: #FF4A4A;
			  color: #FFFFFF;
		  }
	  }
  }
</style>
